<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'地震安全保障服务系统使用情况'" />
          <!-- 仪表盘统计 -->
          <dash-board :data="abSystemUseSituation" />
        </div>
        <div class="app-left-item">
          <subheadings :name="'系统成果统计'" />
          <achievement :statisticsData="abSystemAchievementsStatistics" />
        </div>
        <div class="app-left-item">
          <subheadings :name="'重大活动场所热度榜(频次)'" />
          <hot-list :data="abPlaceHotList" />
        </div>
      </div>
      <!-- 中心部分 -->
      <div class="app-center">
        <!-- 标题 -->
        <headline :name="'全国重大活动安保事件分布图'" />
        <!-- 地图 -->
        <div class="app-map">
          <!-- 系统切换 -->
			    <SystemSelect :styles="{position: 'absolute', top: '-10px', left: '42px' }" />
          <OlMap :refId="'securityActivity'" style="height: 100%" @getMap="getMap"></OlMap>
          <p>
            <img
              src="@/assets/map/image/newImage/blueMarkerSmall.png"
              style="position: relative; top: -210px; scale: 0.8"
            />
            <span style="position: relative; top: -220px; margin-right: 10px; font-size: 14px; color: #ffffff"
              >国家</span
            >
            <img
              src="@/assets/map/image/newImage/redMarkerSmall.png"
              style="position: relative; top: -210px; scale: 0.8"
            />
            <span style="position: relative; top: -220px; font-size: 14px; color: #ffffff">省级</span>
          </p>
          <div ref="popupElement" class="popup-bg" id="map-popup">
            <div class="triangle"></div>
            <div class="popup-head">
              <div class="popup-head-title">重大活动安保</div>
              <div style="cursor: pointer;" class="popup-head-x" @click="hidePopup()">X</div>
            </div>
            <div class="popup-content">
              <div class="popup-table">
                <el-table max-height="150" :data="tableData">
                  <el-table-column prop="name" label="活动名称" :header-align="headerAlign">
                    <template #default="scope">
                      <div class="centered-cell">{{ scope.row.name }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="option" label="操作" :header-align="headerAlign">
                    <template #default="scope">
                      <div style="color: #46ffff;cursor: pointer;" class="centered-cell" @click="gotoActiveInfo(scope.row)">{{ '活动介绍' }}</div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>        
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <div class="app-right-item">
          <!-- 次级标题 -->
          <subheadings :name="'各省累积访问量TOP5'" />
          <Liveness :data="abProvinceActivationRank" />
        </div>
        <div class="app-right-item">
          <subheadings :name="'近五年重大活动安保数量统计'" />
          <LineChart :listData="abActivityNumStatistics" />
        </div>
        <div class="app-right-item">
          <!-- 重大活动安保事件 -->
          <SeamlessScroll :data="abActivityEvents" @typeSwitch="typeSwitch" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Index">
//地图
import IndexMap from '@/views/securityActivity/map/index.vue';
import DashBoard from './components/DashBoard.vue'
import Achievement from './components/Achievement.vue'
import HotList from './components/HotList.vue'
import Liveness from './components/Liveness.vue'
import LineChart from './components/LineChart.vue'
import SeamlessScroll from './components/SeamlessScroll.vue'
import { getActivityMap } from '@/api/securityActivity.js'

// 用户使用情况
const abSystemUseSituation = ref([])
// 系统成果统计
const abSystemAchievementsStatistics = ref([])
// 重大活动场所热度榜
const abPlaceHotList = ref([])
// 各省活跃度排名
const abProvinceActivationRank = ref([])
// 安保数量统计
const abActivityNumStatistics = ref([])
// 安保事件(国家级) abActivityEvents0 省级 abActivityEvents1
const abActivityEvents = ref([])
const abActivityEvents0 = ref([])
const abActivityEvents1 = ref([])

getData()
function getData(){
  getActivityMap().then((res)=>{
    abSystemUseSituation.value = res.data.abSystemYseSituation
    abSystemAchievementsStatistics.value = res.data.abSystemAchievementsStatistics
    abPlaceHotList.value = res.data.abPlaceHotList
    abProvinceActivationRank.value = res.data.abProvinceActivationRank
    abActivityNumStatistics.value = res.data.abActivityNumStatistics
    abActivityEvents.value = res.data.abActivityEvents0
    abActivityEvents0.value = res.data.abActivityEvents0
    abActivityEvents1.value = res.data.abActivityEvents1
  })
}

function typeSwitch(val){
  if(val.value){
    abActivityEvents.value = abActivityEvents0.value
  }else{
    abActivityEvents.value = abActivityEvents1.value
  }
}


import OlMap from '@/components/Olmap';
import { Style, Circle as CircleStyle, Fill, Stroke, Text, Icon } from 'ol/style';
import { Feature } from 'ol';
import { Point } from 'ol/geom';
import Overlay from 'ol/Overlay';
import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import { getChinaBaseMap, getBaseDir } from '@/map/projMap.js';
import { useRouter } from 'vue-router';
import { getMapDate,getIa } from '@/api/securityActivity.js';
import redMarkerSmall from '@/assets/map/image/newImage/redMarkerSmall.png';
import blueMarkerSmall from '@/assets/map/image/newImage/blueMarkerSmall.png';
import popup_img from '@/assets/map/image/newImage/popup-img.png';

const mapInstance = ref(null);
const router = useRouter();
const pointsCountry = ref(null);
const pointsProvince = ref(null);
const pointsLayer = ref(null);
const selectPointData = ref(null);

const mapPopupLayer = ref(null);
const popupElement = ref();
const headerAlign = 'center'; // 设置表头的对齐方式为居中
const tableData = ref([]);

const getMap = (map) => {
  mapInstance.value = map.value;

  addProvinceNameLayer();
  setupSelectInteraction();

  createPopUpLayer();

  getMapData();
};

function getMapData() {
  getMapDate().then((res) => {
    pointsCountry.value = res.data.country;
    pointsProvince.value = res.data.province;
    console.log('==============res: ',res);
    showPointsLayer();
  });
}

function getIaData(provinceCode,type) {
  getIa({provinceCode:provinceCode,type:type}).then((res) => {
    console.log('==============res: ',res);
    setPopupData(res.data);
  });
}

function setPopupData(list) {
  tableData.value.length = 0;
  for (let i = 0; i < list.length; i++) {
    let name = list[i].name;
    let id = list[i].id;
    let iaId = list[i].iaId;
    tableData.value.push({
      name: name,
      iaId: iaId,
      id:id
    });
  }
}

function addProvinceNameLayer() {
  const geojsonSource = new VectorSource({
    url: getChinaBaseMap,
    format: new GeoJSonFormat(),
  });

  // 创建省份名称文本图层
  const textLayer = new VectorLayer({
    source: geojsonSource,
    zIndex: 2,
    style: function (feature) {
      const textstyle = new Style({
        text: new Text({
          font: '10px Calibri,sans-serif',
          fill: new Fill({ color: '#fff' }),
          text: feature.get('name'),
        }),
      });
      return textstyle;
    },
  });

  mapInstance.value.addLayer(textLayer);
}

function showPointsLayer() {
  if(!pointsCountry || !pointsProvince) return;
  if (pointsLayer && pointsLayer.value) {
    mapInstance.value.removeLayer(pointsLayer.value);
  }

  pointsLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 3,
  });

  mapInstance.value.addLayer(pointsLayer.value);

  for( let i=0; i<pointsProvince.value.length; i++ ) {
    let item = pointsProvince.value[i];
    
    const lon = item.longitude;
    const lat = item.latitude;
    const point = new Feature({
      geometry: new Point([lon, lat]),
    });
    const style = new Style({
        image: new Icon({
          src: redMarkerSmall,
          anchor: [0.5, 1],
          scale: 1.0,
        }),
      });
    point.set('type','point_province');
    point.set('point_index',i+'');
    point.setStyle(style);
    pointsLayer.value.getSource().addFeature(point);
  }

  for( let i=0; i<pointsCountry.value.length; i++ ) {
    let item = pointsCountry.value[i];
    
    const lon = item.longitude;
    const lat = item.latitude;
    const point = new Feature({
      geometry: new Point([lon, lat]),
    });
    const style = new Style({
        image: new Icon({
          src: blueMarkerSmall,
          anchor: [0.5, 1],
          scale: 1.0,
        }),
      });
    point.set('type','point_country');
    point.set('point_index',i+'');
    point.setStyle(style);
    pointsLayer.value.getSource().addFeature(point);
  }
}

const createPopUpLayer = () => {
  let popup = document.getElementById('map-popup');
  mapPopupLayer.value = new Overlay({
    element: popup,
    positioning: 'center-left',
    offset: [20, -25], // 偏移量，可根据需要进行调整
    autoPan:true
  });
  mapInstance.value.addOverlay(mapPopupLayer.value);
};

const selectIconFeature = ref(null)
const setupSelectInteraction = () => {
  // 监听地图的点击事件
  mapInstance.value.on('click', (event) => {
    const features = mapInstance.value.getFeaturesAtPixel(event.pixel);
    let pointsSource = pointsLayer.value.getSource();

    //点中了整个图标区域
    if (features.length > 0) {

      const tempFeature = features[0];
      if(tempFeature.get('type') == 'point_country' || tempFeature.get('type') == 'point_province') {//如果点中了大头针区域
        console.log('点击了大头针：');

        let index = Number(tempFeature.get('point_index'));
        let pCode,type;
        if(tempFeature.get('type') == 'point_country'){
          pCode = pointsCountry.value[index].provinceCode;
          type = pointsCountry.value[index].type;
        }else if(tempFeature.get('type') == 'point_province') {
          pCode = pointsProvince.value[index].provinceCode;
          type = pointsProvince.value[index].type;
        }
        getIaData(pCode,type);

        //如果前一个大头针处于放大状态，缩小大头针
        if(selectIconFeature.value) {
          selectIconFeature.value.getStyle().getImage().setScale(1.0);
        }
        selectIconFeature.value = tempFeature;
        const geometry = selectIconFeature.value.getGeometry();
        const coordinates = geometry.getCoordinates();

        //放大大头针
        selectIconFeature.value.getStyle().getImage().setScale(1.2);
        pointsSource.changed();
        popupElement.value.style.display = 'block';
        mapPopupLayer.value.setPosition(coordinates);

      }else if(tempFeature.get('type') == 'popup'){//如果点中弹框区域
      
        console.log('点击了弹框：');
        //这里跳转到工程概况页面

      }

    }else {//点中了大头针和弹框以外的区域，弹框消失，大头针缩小
      console.log('点击了地图：');
      if(selectIconFeature && selectIconFeature.value) {
        selectIconFeature.value.getStyle().getImage().setScale(1.0);
        pointsSource.changed();
        mapPopupLayer.value.setPosition(undefined);
      }
    }
  });
};

function hidePopup() {
  if(mapPopupLayer && mapPopupLayer.value){
    selectIconFeature.value.getStyle().getImage().setScale(1.0);
    pointsLayer.value.getSource().changed();
    mapPopupLayer.value.setPosition(undefined);
  }
}

function gotoActiveInfo(row) {
  router.push({path:'/important',query:{iaId:row.iaId,name:row.name}})
}

/*
const popupFeature = ref(null)
const selectIconFeature = ref(null)
const setupSelectInteraction = () => {
  // 监听地图的点击事件
  mapInstance.value.on('click', (event) => {
    const features = mapInstance.value.getFeaturesAtPixel(event.pixel);
    let pointsSource = pointsLayer.value.getSource();

    //点中了整个图标区域
    if (features.length > 0) {

      const tempFeature = features[0];
      if(tempFeature.get('type') == 'point') {//如果点中了大头针区域
        console.log('点击了大头针：');
        let index = Number(tempFeature.get('pointIndex'));
        selectPointData.value = pointsData.value[index];

        //如果前一个大头针处于放大状态，缩小大头针
        if(selectIconFeature.value) {
          selectIconFeature.value.getStyle().getImage().setScale(1.0);
        }
        selectIconFeature.value = tempFeature;
        const geometry = selectIconFeature.value.getGeometry();
        const coordinates = geometry.getCoordinates();

        //放大大头针
        selectIconFeature.value.getStyle().getImage().setScale(1.2);
        
       if(popupFeature.value) pointsSource.removeFeature(popupFeature.value);

        popupFeature.value = new Feature({
          geometry: new Point([coordinates[0], coordinates[1]])
        });
        const popupStyle1 = new Style({
          image: new Icon({
            src: popup_img, 
            scale: 0.8,
            anchor: [-0.1, 0.6]
          }),
          text: new Text({
            text:selectPointData.value.name,
            font: 'bold 12px Arial',
            fill: new Fill({ color: 'black'}),
            offsetY: -15,
            offsetX: 60,
          })
        });
        const popupStyle2 = new Style({
          text: new Text({
            text: "活动介绍",
            font: '11px Arial',
            fill: new Fill({ color: 'white'}),
            offsetY: 7,
            offsetX: 55,
          })
        });
        popupFeature.value.set('type','popup');
        popupFeature.value.setStyle([popupStyle1,popupStyle2]);
        pointsSource.addFeature(popupFeature.value);

      }else if(tempFeature.get('type') == 'popup'){//如果点中弹框区域
      
        console.log('点击了弹框：');
        //这里跳转到工程概况页面
        router.push({path:'/important',query:selectPointData.value});

      }

    }else {//点中了大头针和弹框以外的区域，弹框消失，大头针缩小
      console.log('点击了地图：');
      selectIconFeature.value.getStyle().getImage().setScale(1.0);
      if(popupFeature.value) pointsSource.removeFeature(popupFeature.value);
    }
  });
};
*/

</script>

<style scoped lang="scss">
.app-main{
  display: flex;
  justify-content: space-between;

  .app-left{
    margin-left: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;
    
    &-item{
      width: 450px;
      height: 360px;
      // background: linear-gradient(135deg, #00032D 0%, #000C58 50%, #00032D 100%);
      // opacity: .85;
      background: linear-gradient(135deg, rgba(0,3,45,.85) 0%, rgba(0,12,88,.85) 50%, rgba(0,3,45,.85) 100%);
      position: relative;
      &::after{
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png')!important;
      }
      &:nth-child(2){
        height: 240px;
      }
      &:nth-child(3){
        height: 300px;
      }
    }
  }

  .app-map{
    width: 960px;
    height:100%;
    //overflow: hidden;//test
    position: relative;
    
  }
  .app-right{
    margin-right: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;
    
    &-item{
      width: 450px;
      height: 300px;
      background: linear-gradient(135deg, rgba(0,3,45,.85) 0%, rgba(0,12,88,.85) 50%, rgba(0,3,45,.85) 100%);
      position: relative;
      &::after{
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png')!important;
      }
    }
  }

  .system-select{
    top: -2px !important;
  }
}

.popup-bg {
  width: 400px;
  height: 275px;
  /* background: linear-gradient(NaNdeg, rgba(5, 12, 53, 0.8) 0%, rgba(4, 16, 89, 0.8) 55%, rgba(6, 40, 150, 0.8) 100%); */
  background: rgba(6, 40, 150, 0.8);
  border-radius: 8px 8px 8px 8px;
  opacity: 1;
  border: 2px solid #0190f9;
  display: flex;
  padding: 17px 15px;
  flex-direction: column;
  position: relative;
  .triangle {
    position: absolute;
    top: 50%;
    left: -10px;
    transform: translateY(-50%);
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #0190f9;
  }
  .popup-head {
    justify-content: center;

    display: flex;
    flex-direction: row;
    font-size: 18px;
    font-family: Source Han Sans CN-Bold, Source Han Sans CN;
    font-weight: bold;
    color: #ffffff;
    line-height: 23px;
    .popup-head-title {
      margin-left: auto;
    }
    .popup-head-x {
      margin-left: auto;
      width: 12px;
      height: 12px;
      color: #e6f4fd;
      opacity: 1;
    }
  }
  .popup-content {
    height: 100%;
    margin-top: 16px;
    display: flex;
    flex-direction: column;
    font-size: 16px;
    font-family: Source Han Sans CN-Medium, Source Han Sans CN;
    font-weight: 500;
    color: #e6f4fd;
    line-height: 23px;
    .popup-content-title {
      background: #050426;
      border-radius: 0px 0px 0px 0px;
      opacity: 0.5;
      padding: 10px 34px;
      justify-content: space-between;
      display: flex;
      flex-direction: row;
    }
    .popup-table {
      width: 100%;
      height: 100%;
      margin-right: 20px;
      .centered-cell {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
      }
      .el-table {
        width: 90%;
        max-height: 150px;
        overflow-x: hidden;
        overflow-y: auto;
        z-index: 99;
        position: absolute;
        /* background: linear-gradient(135deg, #00032d 0%, #000c58 50%, #00032d 100%); */
        /* 背景透明 */
        background: rgba(0, 0, 0, 0);
        :deep(tr:hover > td) {
          background: rgba(71, 90, 219, 0.05) !important;
        }
        // top: 70px;
        // background-color: #00032D;
        /* background: linear-gradient(135deg, #00032d 0%, #000c58 50%, #00032d 100%); */
        :deep(.el-table__header) {
          background: rgba(5, 4, 38, 0.4);
          tr {
            background-color: transparent !important;
          }
          th.el-table__cell {
            background-color: transparent !important;
          }
          th.el-table__cell.is-leaf {
            border-bottom: none;
          }
        }

        :deep(.el-table__row) {
          background: rgba(5, 4, 38, 0.4);
        }
        :deep(.el-table__inner-wrapper)::before {
          display: none;
        }
      }
    }
  }
}

</style>